﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace Pavilion.DesignerTool.ViewTools
{
    public class DragAwareListBoxItem : ListBoxItem
    {
        public event Action<DragAwareListBoxItem> PositionChanged, OffsetChanged;

        public Point? Position { get { return position ?? (position = GetPointOnCenter(this)); } private set { position = value; } }
        public float Offset { get { return offset; } set { offset = value; OnOffsetChanged(); } }

        private float offset;
        private Point? position;

        public void UpdatePosition()
        {
            Position = GetPointOnCenter(this);
            this.OnPositionChanged();
        }

        private void OnOffsetChanged()
        {
            if (OffsetChanged != null)
                OffsetChanged(this);
        }

        private void OnPositionChanged()
        {
            if (PositionChanged != null)
                PositionChanged(this);
        }

        public static Point GetPointOnCenter(FrameworkElement frameworkElement)
        {
            //for now we'll use the top left of the fwe. 

            //get a reference to the custom canvas. This dependency needs to be injected. 
            if (frameworkElement == null)
                return new Point(0, 0);
            else
            {
                var canvas = PavilionVisualTreeHelper.GetAncestor<Canvas>(frameworkElement);

                System.Windows.Media.GeneralTransform transformToCanvasCoordinates = frameworkElement.TransformToAncestor(canvas);
                return transformToCanvasCoordinates.Transform(new Point(frameworkElement.ActualWidth / 2, frameworkElement.ActualHeight / 2));
            }
        }
    }
}
